package com.codeczx.myretrofitdemo.retrofit;

import android.util.Log;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;

/**
 * Created by codeczx on 2018/3/27.
 */

public class BuiltInConverters extends Converter.Factory {

    private static final String TAG = "BuiltInConverters";

    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,Retrofit retrofit) {
        return BufferingResponseBodyConverter.INSTANCE;
    }

    static class ToStringConverter implements Converter<Object, String> {

        static final ToStringConverter INSTANCE = new ToStringConverter();

        @Override
        public String convert(Object value) {
            return value.toString();
        }
    }

    static class BufferingResponseBodyConverter implements Converter<ResponseBody, ResponseBody> {

        static final BufferingResponseBodyConverter INSTANCE = new BufferingResponseBodyConverter();

        @Override
        public ResponseBody convert(ResponseBody value) {
            ResponseBody responseBody = null;
            try {
                responseBody = Utils.buffer(value);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (responseBody != null) {
                    responseBody.close();
                }
            }
            return responseBody;
        }
    }
}
